Use of goto
can lead to programs that are extremely difficult to comprehend and analyse, and possibly to unspecified behavior.
Unfortunately, removing goto
from some code can lead to a rewritten version that is even more difficult to understand than the
original. Therefore, limited use of goto
is sometimes advised.
However, the use of goto
to jump into or out of a sub-block of code, such as into the body of a for
loop is never
acceptable, because it is extremely difficult to understand and will likely yield results other than what is intended.
Noncompliant code example
void f1 (int a) {
if (a <=0) {
goto L2; // Noncompliant; jumps into a different block
}
if (a == 0) {
{
goto L1; // Compliant
}
goto L2; // Noncompliant; jumps into a block
L1:
for (int i = 0; i < a; i++) {
L2:
//... Should only have come here with a >=0. Loop is infinite if a < 0
}
}
Compliant solution
void f1 (int a) {
if (a <=0) {
// ...
}
if (a == 0) {
{
goto L1; // Compliant
}
L1:
for (int i = 0; i < a; i++) {
L2:
//...
}
}